package com.easychat.ai;

import com.easychat.utils.JsonUtils;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 05 2025/5/24
 */
@Service
public class OllamaChatService {
    private static final Logger logger = LoggerFactory.getLogger(OllamaChatService.class);
    private static final String DONE = "[DONE]";
    private static final Integer timeout = 60;
    private static final String AI_URL = "http://localhost:11434/api/generate";

    public String chat(String message){
        logger.info(message);
        HashMap<String, Object> params = new HashMap<>();
        params.put("model","deepseek-r1:1.5b");
        params.put("prompt",message);
        params.put("stream",false);
        String jsonParams = JsonUtils.convertObj2Json(params);
        Request.Builder builder = new Request.Builder().url(AI_URL);
        builder.addHeader("Accept","application/json; charset=utf-8");
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonParams);
        logger.info("请求参数{}", jsonParams);
        Request request = builder.post(body).build();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .build();
        OllamaResponse ollamaResponse=null;
        try{
            Response response = client.newCall(request).execute();
            if(response.isSuccessful() && response.body() != null){
                String res = response.body().string();
                ollamaResponse = JsonUtils.convertJson2Obj(res, OllamaResponse.class);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        logger.info("ai响应返回：{}", JsonUtils.convertObj2Json(ollamaResponse.getResponse()));
        return ollamaResponse == null ?"":ollamaResponse.getResponse();


    }

}
